package com.acme.bankapp.service;

import com.acme.bankapp.domain.Bank;
import com.acme.bankapp.domain.Client;
import com.acme.bankapp.exception.*;

import java.io.*;

/**
 * Created by Student on 14.11.2014.
 */
public class BankService {
    public static void addClient(Bank bank, Client client){
        bank.addClient(client);
    }

    public static Client getClient(Bank bank, String nameClient){

        try {
            for (Client client : bank.getClients()) {
                if (client.getName().equals(nameClient)) {
                    return client;
                }
            }

            throw new ClientNotFoundException(nameClient);
        } catch (ClientNotFoundException e){
            e.printStackTrace();
            return null;
        }
    }

    public static void printClientInfo(Bank bank, String nameClient){
        Client client;
        if( (client = getClient(bank,nameClient)) != null)
            System.out.println(client);
    }

    public static void printClientsInfo(Bank bank){
        for (Client client : bank.getClients()) {
            System.out.println(client);
        }
    }
    public static void saveBank(Bank bank, String fileName) throws IOException {
        saveBank(bank, new FileOutputStream(fileName));
    }

    public static Bank loadBank(String fileName) throws IOException {
        return loadBank(new FileInputStream(fileName));
    }

    public static void saveBank(Bank bank, OutputStream os) throws IOException {
        new ObjectOutputStream(os).writeObject(bank);
    }

    public static Bank loadBank(InputStream is) throws IOException {
        Bank bankFromFile = null;
        ObjectInputStream ois = new ObjectInputStream(is);
        try {
            bankFromFile = (Bank)ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bankFromFile;
    }

    public static void closeListeners(Bank bank) throws IOException {
        bank.closeListeners();
    }
}
